
package com.jiang.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author Administrator
 * @数据库工具类
 */
public class DBUtils {

	// 保证其单例，另外静态方法只能使用静态属性
	private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

	private static final String driver = "oracle.jdbc.driver.OracleDriver";
	private static final String url = "jdbc:oracle:thin:@192.168.117.76:1521:GZJP";
	private static final String user = "scott";
	private static final String db_password = "tiger";

	private DBUtils() {

	}

	/**
	 * @取得数据库连接
	 * @return
	 */
	public static Connection getConnection() {

		Connection connection = threadLocal.get();
		if(connection == null) {
			try {
				Class.forName(driver);
				connection = DriverManager.getConnection(url,user,db_password);
				threadLocal.set(connection);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("数据库连接出现问题");
			}
			return connection;
		}else{
			return connection;
		}
	}
	
	//  关闭连接
	public static void close() {

		try {
			// 关闭远远不够，记得要remove掉，要不然拿到的连接是关闭状态的连接
			Connection conn = threadLocal.get();
			if(conn!=null) {
				conn.close();
				threadLocal.remove();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("获取连接失败!");
		}
		
	}

}
